<template>
  <div class="model-training">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>模型训练管理</span>
          <el-button type="primary" @click="handleCreateTask">
            <el-icon><Plus /></el-icon>新建训练任务
          </el-button>
        </div>
      </template>

      <!-- 训练任务列表 -->
      <el-table :data="trainingTasks" style="width: 100%">
        <el-table-column prop="name" label="任务名称" min-width="150" />
        <el-table-column prop="modelType" label="模型类型" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="200">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :status="getProgressStatus(row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleViewTask(row)">
                查看
              </el-button>
              <el-button
                type="primary"
                link
                :disabled="!['pending', 'failed'].includes(row.status)"
                @click="handleEditTask(row)"
              >
                编辑
              </el-button>
              <el-button type="primary" link @click="handleViewLogs(row)">
                日志
              </el-button>
              <el-button
                type="danger"
                link
                :disabled="!['pending', 'failed'].includes(row.status)"
                @click="handleDeleteTask(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 任务详情对话框 -->
    <el-dialog
      v-model="taskDialogVisible"
      :title="taskDialogType === 'create' ? '新建训练任务' : '编辑训练任务'"
      width="800px"
    >
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="120px"
      >
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="模型类型" prop="modelType">
          <el-select v-model="taskForm.modelType" placeholder="请选择模型类型">
            <el-option label="XGBoost" value="xgboost" />
            <el-option label="LightGBM" value="lightgbm" />
            <el-option label="Random Forest" value="random_forest" />
            <el-option label="LSTM" value="lstm" />
          </el-select>
        </el-form-item>
        <el-form-item label="特征选择" prop="features">
          <el-select
            v-model="taskForm.features"
            multiple
            placeholder="请选择特征"
          >
            <el-option
              v-for="feature in availableFeatures"
              :key="feature.id"
              :label="feature.name"
              :value="feature.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="训练参数">
          <el-collapse>
            <el-collapse-item title="基础参数" name="1">
              <el-form-item label="学习率">
                <el-input-number
                  v-model="taskForm.params.learningRate"
                  :step="0.01"
                  :min="0"
                  :max="1"
                />
              </el-form-item>
              <el-form-item label="迭代次数">
                <el-input-number
                  v-model="taskForm.params.iterations"
                  :step="100"
                  :min="100"
                />
              </el-form-item>
              <el-form-item label="批次大小">
                <el-input-number
                  v-model="taskForm.params.batchSize"
                  :step="32"
                  :min="32"
                />
              </el-form-item>
            </el-collapse-item>
            <el-collapse-item title="高级参数" name="2">
              <el-form-item label="早停轮数">
                <el-input-number
                  v-model="taskForm.params.earlyStopping"
                  :step="10"
                  :min="0"
                />
              </el-form-item>
              <el-form-item label="交叉验证">
                <el-input-number
                  v-model="taskForm.params.crossValidation"
                  :step="1"
                  :min="2"
                  :max="10"
                />
              </el-form-item>
              <el-form-item label="随机种子">
                <el-input-number
                  v-model="taskForm.params.randomSeed"
                  :step="1"
                />
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="taskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTaskSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 训练日志对话框 -->
    <el-dialog
      v-model="logDialogVisible"
      title="训练日志"
      width="800px"
    >
      <el-timeline>
        <el-timeline-item
          v-for="log in trainingLogs"
          :key="log.id"
          :type="getLogType(log.level)"
          :timestamp="log.time"
        >
          {{ log.message }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 训练任务数据
const trainingTasks = ref([
  {
    id: 1,
    name: '设备故障预测模型',
    modelType: 'XGBoost',
    status: 'running',
    progress: 65,
    createTime: '2024-03-17 10:00:00'
  },
  {
    id: 2,
    name: '能耗预测模型',
    modelType: 'LSTM',
    status: 'completed',
    progress: 100,
    createTime: '2024-03-16 15:30:00'
  },
  {
    id: 3,
    name: '异常检测模型',
    modelType: 'Random Forest',
    status: 'failed',
    progress: 30,
    createTime: '2024-03-15 09:15:00'
  }
])

// 可用特征
const availableFeatures = ref([
  { id: 1, name: '温度' },
  { id: 2, name: '湿度' },
  { id: 3, name: '压力' },
  { id: 4, name: '振动' }
])

// 对话框相关
const taskDialogVisible = ref(false)
const taskDialogType = ref('create')
const taskFormRef = ref(null)
const taskForm = reactive({
  name: '',
  modelType: '',
  features: [],
  params: {
    learningRate: 0.1,
    iterations: 1000,
    batchSize: 64,
    earlyStopping: 50,
    crossValidation: 5,
    randomSeed: 42
  }
})

const taskRules = {
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  modelType: [
    { required: true, message: '请选择模型类型', trigger: 'change' }
  ],
  features: [
    { required: true, message: '请选择特征', trigger: 'change' }
  ]
}

// 训练日志
const logDialogVisible = ref(false)
const trainingLogs = ref([
  {
    id: 1,
    time: '2024-03-17 10:00:00',
    level: 'info',
    message: '开始训练任务：设备故障预测模型'
  },
  {
    id: 2,
    time: '2024-03-17 10:01:00',
    level: 'info',
    message: '加载训练数据...'
  },
  {
    id: 3,
    time: '2024-03-17 10:02:00',
    level: 'warning',
    message: '发现异常值，已自动处理'
  },
  {
    id: 4,
    time: '2024-03-17 10:05:00',
    level: 'info',
    message: '开始模型训练...'
  },
  {
    id: 5,
    time: '2024-03-17 10:10:00',
    level: 'error',
    message: '训练过程中出现错误，正在重试...'
  }
])

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    running: 'warning',
    completed: 'success',
    failed: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取进度状态
const getProgressStatus = (status) => {
  if (status === 'completed') return 'success'
  if (status === 'failed') return 'exception'
  return ''
}

// 获取日志类型
const getLogType = (level) => {
  const levelMap = {
    info: 'primary',
    warning: 'warning',
    error: 'danger'
  }
  return levelMap[level] || 'info'
}

// 处理函数
const handleCreateTask = () => {
  taskDialogType.value = 'create'
  taskDialogVisible.value = true
  Object.assign(taskForm, {
    name: '',
    modelType: '',
    features: [],
    params: {
      learningRate: 0.1,
      iterations: 1000,
      batchSize: 64,
      earlyStopping: 50,
      crossValidation: 5,
      randomSeed: 42
    }
  })
}

const handleViewTask = (task) => {
  // TODO: 实现查看任务详情功能
  ElMessage.info('查看任务详情功能开发中...')
}

const handleEditTask = (task) => {
  taskDialogType.value = 'edit'
  taskDialogVisible.value = true
  Object.assign(taskForm, task)
}

const handleDeleteTask = (task) => {
  ElMessageBox.confirm(
    '确定要删除该训练任务吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 实现删除功能
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleViewLogs = (task) => {
  logDialogVisible.value = true
  // TODO: 加载任务日志
}

const handleTaskSubmit = async () => {
  if (!taskFormRef.value) return
  
  await taskFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现保存功能
      ElMessage.success(taskDialogType.value === 'create' ? '创建成功' : '更新成功')
      taskDialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.model-training {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-collapse-item__header) {
  font-size: 14px;
  font-weight: bold;
}
</style> 